import re
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from .models import User
from django.conf import settings
from .constants import VERIFY_EMAIL_TOKEN_EXPIRES
def jwt_response_payload_handler(token, user=None, request=None):
    """自定义JWT验证成功返回数据"""
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """根据账号信息获取用户"""
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            # 账号为手机号
            user = User.objects.filter(mobile=account).get()
        else:
            # 账号为用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        自定义用户认证
        :param request: 本次请求对象
        :param username: 用户名或手机号
        :param password: 登陆密码
        :return:
        """
        user = get_user_by_account(username)
        # 判断密码
        if user and user.check_password(password):
            return user


def check_verify_email_token(token):
    """校验邮箱验证token"""
    serializer = Serializer(settings.SECRET_KEY, VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
        return data['user_id']
    except BadData:
        return None
